package kr.hkit.calendarproject12;

import java.util.ArrayList;
import java.util.Calendar;

import kr.hkit.calendarproject12.DAO.DAO;
import kr.hkit.calendarproject12.DTO.InputWord;
import kr.hkit.calendarproject12.DTO.MyItem;
import kr.hkit.calendarproject12.Fragment.MonthCalendar;
import kr.hkit.calendarproject12.MyDBHelper.MyDBHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;

public class Detail extends Activity { // 일정목록 추가하기
	final static String TAG = "DATE";
	MyDBHelper mDBHelper;
	DAO dao;
	Calendar calendar;
	ArrayList<MyItem> arList;	//DB에서 처리. Dao작업예정
	EditText editTitle, startDate, startTime, intervalTime, editMemo;
	Button inputInterval, btnSave, btnCancel, btnDelete;
	Cursor cursor;
	int mSelect = 0;
	String todayTitle, todayStartDate, todayStartTime, todayMemo;
	int todayAlarmInterval;
	String cTodayTitle, cTodayStartDate, cTodayStartTime, cTodayMemo;
	int cTodayAlarmInterval;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(TAG, "onCreate() - activity");
		super.onCreate(savedInstanceState);
		setContentView(R.layout.detail);

		//날짜를 가져옴
		calendar = Calendar.getInstance();
		
		//EditText
		editTitle = (EditText) findViewById(R.id.edittitle);
		startDate = (EditText) findViewById(R.id.startdate);
		startTime = (EditText) findViewById(R.id.starttime);
		intervalTime = (EditText) findViewById(R.id.intervalmin);		
		editMemo = (EditText) findViewById(R.id.editmemo);

		//Button
		inputInterval = (Button) findViewById(R.id.intervalbutton);
		btnSave = (Button) findViewById(R.id.btnsave);
		btnDelete = (Button) findViewById(R.id.btndel);
		btnCancel = (Button) findViewById(R.id.btncancel);
			
		//해당 날짜의 정보를 intent로 받아옴
		//만약 제목과 select한 쿼리의 제목이 일치하는 내용을 setText해줌
		Intent intent = getIntent();
		todayTitle = intent.getStringExtra("ParamTitle");
		todayStartDate = intent.getStringExtra("ParamStartDate");
		todayStartTime = intent.getStringExtra("ParamStartTime");
		todayAlarmInterval = intent.getIntExtra("ParamAlarmInterval", 1);
		todayMemo = intent.getStringExtra("ParamMemo");
		
		mDBHelper = new MyDBHelper(this);
		SQLiteDatabase db = mDBHelper.getReadableDatabase();
		String sql = "Select title, startDate, startTime, alarmInterval, memo from today where title='" + todayTitle + "' and startDate='" + todayStartDate + "';";
		cursor = db.rawQuery(sql, null);
		
		if (cursor.moveToNext()) {
			editTitle.setText(todayTitle);
			startDate.setText(todayStartDate);
			startTime.setText(todayStartTime);
			intervalTime.setText(String.valueOf(todayAlarmInterval));
			editMemo.setText(todayMemo);
			btnDelete.setVisibility(View.VISIBLE);
		} else {
			startDate.setText(MonthCalendar.currentDate);
			btnDelete.setVisibility(View.INVISIBLE);
		}
		
		mDBHelper.close();
	}

	public void mOnClick(View v) {		
		switch (v.getId()) {
		//알림간격 다이얼로그 버튼 이벤트처리
		case R.id.intervalbutton:
			new AlertDialog.Builder(this)
					.setTitle("알림간격 선택")
					.setSingleChoiceItems(R.array.minutes, mSelect,
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									mSelect = which;
								}

							})
					.setPositiveButton("확인",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int whichButton) {
									String[] minutes = getResources()
											.getStringArray(R.array.minutes);
									intervalTime.setText(minutes[mSelect]);
								}

							}).setNegativeButton("취소", null).show();
			break;
			
		//스케쥴 날짜 설정 다이얼로그
		case R.id.startdate:
			new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
				@Override
				public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
					startDate.setText(year+"/" + (monthOfYear + 1)+"/" + dayOfMonth);
				}
			}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH)).show();

			break;

		//스케쥴 시간 설정 다이얼로그
		case R.id.starttime:
			new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() {
				@Override
				public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
					startTime.setText(hourOfDay + ":" + minute);
				}
			}, calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE), true).show();
			
			break;

		//스케쥴 저장 및 업데이트 이벤트 처리
		case R.id.btnsave:			
			dao = DAO.open(getApplication());
			arList = dao.setTextFromTodaySchedule(todayTitle);
			
			cTodayTitle = editTitle.getText().toString();
			cTodayStartDate = startDate.getText().toString();
			cTodayStartTime = startTime.getText().toString();
			cTodayAlarmInterval = Integer.parseInt(intervalTime.getText().toString());
			cTodayMemo = editMemo.getText().toString();
			
			if (arList.size() == 0) {
								
				try {
					validCheck(cTodayTitle, cTodayStartDate, cTodayStartTime);
					dao.insertSchedule(cTodayTitle, cTodayStartDate, cTodayStartTime, cTodayAlarmInterval, cTodayMemo);
					Log.d(TAG, "saveBtn - insert activity");
					
					Intent intent = new Intent(getApplication(), MainActivity.class);
					startActivity(intent);
					
					Toast.makeText(getApplicationContext(), InputWord.INSERT_COMPLETE, Toast.LENGTH_SHORT).show();
					
					finish();
							
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "제목, 날짜 및 시간은 필수 입력사항입니다.", Toast.LENGTH_SHORT).show();
				}
				
			} else {
				
				try {
					validCheck(cTodayTitle, cTodayStartDate, cTodayStartTime);
					dao.updateSchedule(cTodayTitle, cTodayStartDate, cTodayStartTime, cTodayAlarmInterval, cTodayMemo, todayTitle, todayStartDate);
					Log.d(TAG, "saveBtn - update activity");
					
					Intent intent = new Intent(getApplication(), MainActivity.class);
					startActivity(intent);
					
					Toast.makeText(getApplicationContext(), InputWord.UPDATE_COMPLETE, Toast.LENGTH_SHORT).show();
					
					finish();
					
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), "제목, 날짜 및 시간은 필수 입력사항입니다.", Toast.LENGTH_SHORT).show();
				}
				
			}
			
			dao.close();
			
			break;
			
		case R.id.btndel:
			dao = DAO.open(getApplication());
			
			dao.deleteSchedule(todayTitle, todayStartDate);
			Log.d(TAG, "delBtn - delete activity");

			Intent intent = new Intent(getApplication(), MainActivity.class);
			startActivity(intent);
			
			Toast.makeText(getApplicationContext(), InputWord.DELETE_COMPLETE, Toast.LENGTH_SHORT).show();
					
			dao.close();
			finish();
			break;
			
		case R.id.btncancel:
			finish();
			break;
		}
		
	}

	public void validCheck(String title, String startDate, String startTime) throws Exception {
		if(title.equals("")){
			throw new Exception("제목을 입력!");
		}
		if(startDate.equals("")){
			throw new Exception("날짜 입력");
		}
		if(startTime.equals("")){
			throw new Exception("시간 입력!");
		}
	}

}

